<template>
  <div>
    <ul class="list-container">
      <li v-for="(item) in items" :key="item.id" @dblclick="enterEdit(item)"
        :class="{ editing: item.isEditing }">
        <div v-if="item.isEditing" class="edit-wrapper">
          <input ref="input" v-model.trim="item.name" @blur="handleBlur(item)" @keyup.enter="handleBlur(item)"
            class="edit-input" />
          <div v-if="item.error" class="error-tip">{{ item.error }}</div>
        </div>
        <span v-else class="name-text">{{ item.name }}</span>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'listEdit',
  data() {
    return {
      items: [
        { id: 1, name: 'Item 1', isEditing: false, error: '' },
        { id: 2, name: 'Item 2', isEditing: false, error: '' },
        { id: 3, name: 'Long Example Item', isEditing: false, error: '' }
      ]
    }
  },
  methods: {
    enterEdit(currentItem) {
      this.items.forEach(item => {
        // 关闭所有其他项的编辑状态
        item.isEditing = item.id === currentItem.id
        item.error = '' // 清除旧错误信息
      })

      this.$nextTick(() => {
        // 自动聚焦到输入框
        const inputRef = this.$refs.input?.find(
          // ref => ref.$el?.dataset?.index === currentItem.id.toString()
          ref => {
            console.log('ref.$el?.dataset', ref.$el?.dataset)
          }
        )
        console.log('inputRef', this.$refs.input)
        this.$refs.input[0].focus()
        if (inputRef) {
          inputRef.focus()
        }
      })
    },

    validate(item) {
      if (!item.name) {
        return 'Name cannot be empty'
      }
      if (item.name.length > 10) {
        return 'Name cannot exceed 10 characters'
      }
      return ''
    },

    handleBlur(item) {
      const error = this.validate(item)
      if (error) {
        item.error = error
        // 保持编辑状态直到输入合法
        return
      }
      item.isEditing = false
      item.error = ''
    }
  }
}
</script>

<style scoped>
.list-container {
  list-style: none;
  padding: 0;
  max-width: 400px;
}

li {
  padding: 12px;
  margin: 8px 0;
  border: 1px solid #eee;
  border-radius: 4px;
  transition: all 0.3s;
}

li.editing {
  border-color: #409eff;
}

.name-text {
  cursor: text;
}

.edit-wrapper {
  position: relative;
}

.edit-input {
  padding: 6px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  width: 100%;
}

.error-tip {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 4px;
}
</style>